//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Galleries.Components;

namespace CommunityServer.Galleries.Controls
{
	/// <summary>
	/// Summary description for TagCloud.
	/// </summary>
	public class TagCloud : CommunityServer.Controls.BaseTagCloud
	{
		protected override ArrayList Tags
		{
			get
			{
				if (tags == null)
				{
					if (this.FilterTags != null)
						tags = CommunityServer.Components.Tags.GetTagsBySection(this.CurrentGallery.SectionID, this.FilterTags);
					else
						tags = CommunityServer.Components.Tags.GetTagsBySection(this.CurrentGallery.SectionID);
				}

				return tags;
			}
		}

		protected override string GetTagUrl(string tagName)
		{
			if (this.FilterTags == null)
				return GalleryUrls.Instance().TagsBrowser(this.CurrentGallery.ApplicationKey, new String[] {tagName});
			else
			{
				ArrayList linkTags = new ArrayList(this.FilterTags);
				linkTags.Add(tagName);
				return GalleryUrls.Instance().TagsBrowser(this.CurrentGallery.ApplicationKey, (string[]) linkTags.ToArray(typeof(string)));
			}
		}

		#region Gallery Properties

		private Gallery gallery = null;

		/// <summary>
		/// Returns the CurrentWeb and calls Authorize
		/// </summary>
		public virtual Gallery CurrentGallery
		{
			get
			{
				if(gallery == null)
				{
					string appKey = CSContext.Current.ApplicationKey;
					if(Globals.IsNullorEmpty(appKey))
						appKey = GalleryConfiguration.Instance().DefautApplicationKey;

					gallery = Galleries.GetGallery(appKey);

					if(!CurrentUser.IsGalleryAdministrator)
					{
						Authorize(gallery);
					}

				}

				return gallery;
			}
		}

		protected User CurrentUser
		{
			get{return csContext.User;}
		} 

		protected virtual void Authorize(Gallery g)
		{
			if(g == null)
				throw new CSException(CSExceptionType.SectionNotFound, string.Format("Gallery {0} could not be found", CSContext.Current.ApplicationKey));


			if(Context.Items[CurrentUser.Username + "Permission:" + Permission.View.ToString()] == null)
			{
				Permissions.AccessCheck(g,Permission.View,this.CurrentUser);
				Context.Items[CurrentUser.Username + "Permission:" + Permission.View.ToString()] = true;

			}
		}

		#endregion
	}
}
